package com.servlet.contacts;

import java.io.IOException;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.listener.ContextListener;
import com.servlet.model.base.Contact;
import com.servlet.model.base.Profile;
import com.servlet.model.database.BaseAcces;

/**
 * Servlet appelée lors de la suppression d'un contact depuis la page de contacts
 * @author Marc Bouffard
 */
public class SupprimerContact extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{	
		HttpSession session = request.getSession();
		
		BaseAcces base = ContextListener.base;
		String email = (String) session.getAttribute("email");

		int num = Integer.parseInt( request.getParameter("numC") );
		ArrayList<Profile> a = (ArrayList<Profile>)(session.getAttribute("contactsAppuie"));

		session.setAttribute("contactsAppuie",  null );

		ArrayList<Contact> contacts = base.findContacts(email);
		Contact c = null;
		for( int i = 0 ; i < contacts.size() ; i++ )
		{
			if( (contacts.get(i).getEmail_user1().compareTo(email) == 0 && contacts.get(i).getEmail_user2().compareTo(a.get(num).getEmail()) == 0 ) || 
					(contacts.get(i).getEmail_user2().compareTo(email) == 0 && contacts.get(i).getEmail_user1().compareTo(a.get(num).getEmail()) == 0 ) )
			{
				c = contacts.get(i);
			}
				
		}
		base.removeContact(c);

		java.util.Date dd = Calendar.getInstance().getTime();
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String dat = dateFormat.format(dd);
		Date date = Date.valueOf(dat);
		
		base.addNews( email , a.get(num).getEmail() , date, 4 );
		
		base.addNews( a.get(num).getEmail() , email , date, 4 );

		response.sendRedirect("contacts?indice=" + session.getAttribute("numero_page"));
	}
}
